﻿using System;
using System.Globalization;
using System.Text;
using System.Web.UI;
using System.Web.UI.WebControls;
using mojoPortal.Business;
using mojoPortal.Business.WebHelpers;
using mojoPortal.Web.Framework;
using mojoPortal.Web;
using Resources;
using ud_Article.Business;
using System.Collections.Generic;
using ud_Utilities;

namespace ud_Article.UI
{
    public partial class SlideTabLoader : UserControl
    {
        #region Properties

        private int pageNumber = 1;
        private int totalPages = 1;
        protected string EditContentImage = WebConfigSettings.EditContentImage;
        protected string EditBlogAltText = "Edit";
        protected Double TimeOffset;
        private TimeZoneInfo timeZone;
        protected DateTime CalendarDate;
        protected bool ShowGoogleMap = true;
        protected string FeedBackLabel = string.Empty;
        protected string GmapApiKey = string.Empty;
        protected bool EnableContentRating;
        protected string disqusFlag = string.Empty;
        protected string IntenseDebateAccountId = string.Empty;
        protected bool ShowCommentCounts = true;
        protected string EditLinkText = ArticleResources.BlogEditEntryLink;
        protected string EditLinkTooltip = ArticleResources.BlogEditEntryLink;
        protected string EditLinkImageUrl = string.Empty;
        private mojoBasePage basePage;
        private Module module;
        protected ArticleConfiguration config = new ArticleConfiguration();
        private int pageId = -1;
        private int moduleId = -1;
        private string siteRoot = string.Empty;
        private string imageSiteRoot = string.Empty;
        private SiteSettings siteSettings;
        private string[] listModuleId;
        private int categoryId = -1;

        public int CategoryId
        {
            get { return categoryId; }
            set { categoryId = value; }
        }

        public string[] ListModuleId
        {
            get { return listModuleId; }
            set { listModuleId = value; }
        }

        public int PageId
        {
            get { return pageId; }
            set { pageId = value; }
        }

        public int ModuleId
        {
            get { return moduleId; }
            set { moduleId = value; }
        }

        public string SiteRoot
        {
            get { return siteRoot; }
            set { siteRoot = value; }
        }

        public string ImageSiteRoot
        {
            get { return imageSiteRoot; }
            set { imageSiteRoot = value; }
        }

        public ArticleConfiguration Config
        {
            get { return config; }
            set { config = value; }
        }

        public bool IsEditable { get; set; }

        #endregion


        protected override void OnInit(EventArgs e)
        {
            base.OnInit(e);
            Load += Page_Load;
            EnableViewState = false;
            //pgr.Command += new CommandEventHandler(pgr_Command);
        }

        protected virtual void Page_Load(object sender, EventArgs e)
        {

            LoadSettings();

#if !MONO
            if (!(Page is mojoPortal.Web.UI.Pages.MyPage))
            {
                SetupRssLink();
            }
#endif

            PopulateLabels();
            if (!Page.IsPostBack)
            {
                PopulateControls();
            }

        }

        private void PopulateControls()
        {
            BindBlogs();
            BindOthers();
        }

        private void BindOthers()
        {
            pnlMoreLink.Visible = config.OtherArticlesShowMoreLinkSetting && rptBlogs.Items.Count > 0;
            if (!pnlMoreLink.Visible) return;
            hplMoreLink.Text = config.OtherArticlesMoreLinkTextSetting;
            hplMoreLink.NavigateUrl = config.OtherArticlesMoreLinkSetting;
        }

        public void BindBlogs()
        {
            DBArticleLinq repository = new DBArticleLinq();
            List<Business.ud_Article> result;
            if (listModuleId != null && listModuleId[0].Length > 0)
            {
                result = config.UseHotArticle
                             ? repository.GetPageHotModule(listModuleId, config.PageSize, pageNumber, out totalPages)
                             : config.UseSlideArticle || config.UseTabArticle
                             ? repository.GetPageModule(listModuleId, config.PageSize, pageNumber, out totalPages)
                             : repository.GetPageMostViewModule(listModuleId, config.PageSize, pageNumber, out totalPages);
            }
            else
            {
                result = categoryId.Equals(0)
                         ? repository.GetPageByModuleId(moduleId, config.PageSize,
                                                        pageNumber, out totalPages)
                         : repository.GetPageCategory(categoryId, config.PageSize,
                                                      pageNumber, out totalPages);
            }
            rptTabs.DataSource = result;
            rptTabs.DataBind();
            rptBlogs.DataSource = result;
            rptBlogs.DataBind();
        }

        protected virtual void PopulateLabels()
        {
            EditBlogAltText = ArticleResources.EditImageAltText;
            FeedBackLabel = ArticleResources.BlogFeedbackLabel;

            mojoBasePage mojoBasePage = Page as mojoBasePage;
            if (mojoBasePage == null) return;
            if (!mojoBasePage.UseTextLinksForFeatureSettings)
            {
                EditLinkImageUrl = ImageSiteRoot + "/Data/SiteImages/" + EditContentImage;
            }
        }

        protected string FormatPostAuthor(string userGuid)
        {
            return ArticleUtils.FormatPostAuthor(userGuid, config);
        }

        protected string FormatBlogDate(DateTime startDate)
        {
            return ArticleUtils.FormatBlogDate(startDate, config, timeZone, TimeOffset);
        }

        protected string BuildEditUrl(int itemID)
        {
            return ArticleUtils.BuildEditUrl(itemID, listModuleId, SiteRoot, PageId, ModuleId);
        }

        private string GetRssUrl()
        {
            return ArticleUtils.GetRssUrl(config, SiteRoot, ModuleId);
        }

        protected virtual void LoadSettings()
        {
            SetJQueryScript();
            siteSettings = CacheHelper.GetCurrentSiteSettings();
            TimeOffset = SiteUtils.GetUserTimeOffset();
            timeZone = SiteUtils.GetUserTimeZone();
            GmapApiKey = SiteUtils.GetGmapApiKey();
            pageNumber = WebUtils.ParseInt32FromQueryString("pagenumber", pageNumber);
            divblog.CssClass += " mojo-tabs-slide" + moduleId; 
            if (Page is mojoBasePage)
            {
                basePage = Page as mojoBasePage;
                module = basePage.GetModule(moduleId);
            }

            CalendarDate = WebUtils.ParseDateFromQueryString("blogdate", DateTime.UtcNow).Date;

            if (CalendarDate > DateTime.UtcNow.Date)
            {
                CalendarDate = DateTime.UtcNow.Date;
            }

            if ((config.UseExcerpt) && (!config.GoogleMapIncludeWithExcerpt)) { ShowGoogleMap = false; }

            EnableContentRating = config.EnableContentRating;
            if (config.UseExcerpt) { EnableContentRating = false; }

            IntenseDebateAccountId = config.IntenseDebateAccountId.Length > 0 ? config.IntenseDebateAccountId : siteSettings.IntenseDebateAccountId;

            if (config.AllowComments)
            {
                if ((IntenseDebateAccountId.Length > 0) && (config.CommentSystem == "intensedebate"))
                {
                    ShowCommentCounts = false;
                }
            }

            if (config.Copyright.Length > 0)
            {
                lblCopyright.Text = config.Copyright;
            }

            if (IsEditable)
            {
                Article.CountOfDrafts(ModuleId);
            }
        }

        private void SetJQueryScript()
        {
            StringBuilder sb = ArticleUtils.SetJQueryScript(config, moduleId);
            if (!Page.ClientScript.IsStartupScriptRegistered(typeof(Page), "postlist" + moduleId) && sb.ToString() != string.Empty)
            {
                Page.ClientScript.RegisterStartupScript(typeof(Page), "postlist" + moduleId, sb.ToString());
            }
            if (Page.ClientScript.IsStartupScriptRegistered(typeof(Page), "jquerytool")) return;
            string script = "<script src='" + imageSiteRoot + "/ClientScript/jqmojo/jquery.tools.min.js'></script>";
            Page.ClientScript.RegisterStartupScript(typeof(Page), "jquerytool", script);
        }

        protected virtual void SetupRssLink()
        {
            if (WebConfigSettings.DisableBlogRssMetaLink) { return; }
            if (module == null || Page.Master == null) return;
            Control head = Page.Master.FindControl("Head1");
            if (head == null) return;
            Literal rssLink = new Literal
                                  {
                                      Text = @"<link rel=""alternate"" type=""application/rss+xml"" title="""
                                             + module.ModuleTitle + @""" href="""
                                             + GetRssUrl() + @""" />"
                                  };
            head.Controls.Add(rssLink);
        }
    }
}